package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }
    @Autowired
    private IElderService elderService;
    @Autowired
    private IBedService  bedService;
    @Autowired
    private IContractService  contractService;
    @Autowired
    private ICheckInService checkInService;
    @Autowired
    private ICheckInConfigService  checkInConfigService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //检查老人是否已入住？
        Elder older = elderService.lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .one();
        if (older != null && older.getStatus()==1){
            throw new BaseException("该老人已入住");
        }
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.getById(bedId);
        if (bed==null){
            throw new BaseException("床位不存在");
        }
        bed.setBedStatus(1);
        bedService.updateById(bed);
        //新增或者更新老人
        Elder elder = BeanUtil.toBean(dto.getCheckInElderDto(), Elder.class);
        if (older!=null){
            elder.setId(older.getId());
        }
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        elder.setStatus(1);
        elder.setBedId(bedId);
        elder.setBedNumber(bed.getBedNumber());
        elderService.saveOrUpdate(elder);
        //新增签约办理
        Contract contract= BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setElderId((int)elder.getId().longValue());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        LocalDateTime start=dto.getCheckInConfigDto().getStartDate();
        LocalDateTime end= dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(start);
        contract.setEndDate(end);
        contract.setStatus(LocalDateTime.now().isAfter(start)?1:0);
        //contract.setSignDate(LocalDateTime.now());
        contractService.save(contract);
        //新增入住信息
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        //新增入住配置
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
    }

    @Override
    public CheckInDetailVo lookDetail(Long id) {
        //新建返回对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(BeanUtil.toBean(elderService.getById(id), CheckInElderVo.class));
        CheckIn checkIn = checkInService.lambdaQuery().eq(CheckIn::getElderId,id).one();
        CheckInConfig one = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(one,CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        String famileMessage = checkIn.getRemark();
        List<ElderFamilyVo> list = JSONUtil.toList(famileMessage, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(list);
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, id).one();
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
